#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.template import TemplateSyntaxError,TemplateDoesNotExist,Library
from django.conf import settings
from django.template.base import Library, Node, TextNode
from django.template.loader_tags import BlockContext,ExtendsNode,BlockNode
from django.template.loader import select_template, get_template, get_template_from_string, find_template

register = Library()

BLOCK_CONTEXT_KEY = 'block_context'

##class ThemeExtendsNode(ExtendsNode):
##    must_be_first = False
##	
##    def __init__(self, nodelist, parent_name, parent_name_expr, template_dirs=None):
##        self.nodelist = nodelist
##        self.parent_name, self.parent_name_expr = parent_name, parent_name_expr
##        self.template_dirs = template_dirs
##		
##		
##    def get_parent(self, context):
##        if self.parent_name_expr:
##            self.parent_name = self.parent_name_expr.resolve(context)
##        parent = theme_template_url() +'/'+ self.parent_name
##        if not parent:
##            error_msg = "Invalid template name in 'extends' tag: %r." % parent
##            if self.parent_name_expr:
##                error_msg += " Got this from the '%s' variable." % self.parent_name_expr.token
##            raise TemplateSyntaxError, error_msg
##        try:
##            source, origin = find_template(parent, self.template_dirs)
##            print parent, self.template_dirs
##            print source, origin
##        except TemplateDoesNotExist:
##            raise TemplateSyntaxError, "Template %r cannot be extended, because it doesn't exist" % parent
##        else:
##            return get_template_from_string(source, origin, parent)
##        #
##        #try:
##        #    return select_template(parent)
##        #except TemplateDoesNotExist:
##        #    raise TemplateSyntaxError, "Template %r cannot be extended, because it doesn't exist" % parent

#TODO 暂时的修补方法，之后修改为继承的方法实现
class ThemeExtendsNode(Node):
    must_be_first = False

    def __init__(self, nodelist, parent_name, parent_name_expr, template_dirs=None):
        self.nodelist = nodelist
        self.parent_name, self.parent_name_expr = parent_name, parent_name_expr
        self.template_dirs = template_dirs
        self.blocks = dict([(n.name, n) for n in nodelist.get_nodes_by_type(BlockNode)])

    def __repr__(self):
        if self.parent_name_expr:
            return "<ExtendsNode: extends %s>" % self.parent_name_expr.token
        return '<ExtendsNode: extends "%s">' % self.parent_name

    def get_parent(self, context):
        if self.parent_name_expr:
            self.parent_name = self.parent_name_expr.resolve(context)
        parent = theme_template_url() +'/'+ self.parent_name
        #parent = self.parent_name
        if not parent:
            error_msg = "Invalid template name in 'extends' tag: %r." % parent
            if self.parent_name_expr:
                error_msg += " Got this from the '%s' variable." % self.parent_name_expr.token
            raise TemplateSyntaxError(error_msg)
        if hasattr(parent, 'render'):
            return parent # parent is a Template object
        return get_template(parent)

    def render(self, context):
        compiled_parent = self.get_parent(context)

        if BLOCK_CONTEXT_KEY not in context.render_context:
            context.render_context[BLOCK_CONTEXT_KEY] = BlockContext()
        block_context = context.render_context[BLOCK_CONTEXT_KEY]

        # Add the block nodes from this node to the block context
        block_context.add_blocks(self.blocks)

        # If this block's parent doesn't have an extends node it is the root,
        # and its block nodes also need to be added to the block context.
        for node in compiled_parent.nodelist:
            # The ExtendsNode has to be the first non-text node.
            if not isinstance(node, TextNode):
                if not isinstance(node, ExtendsNode):
                    blocks = dict([(n.name, n) for n in
                                   compiled_parent.nodelist.get_nodes_by_type(BlockNode)])
                    block_context.add_blocks(blocks)
                break

        # Call Template._render explicitly so the parser context stays
        # the same.
        return compiled_parent._render(context)



def do_theme_extends(parser,token):
    """
    template based extends
    """
    bits = token.contents.split()
    if len(bits) != 2:
        raise TemplateSyntaxError, "'%s' takes one argument" % bits[0]
    parent_name, parent_name_expr = None, None
    if bits[1][0] in ('"', "'") and bits[1][-1] == bits[1][0]:
        parent_name = bits[1][1:-1]
    else:
        parent_name_expr = parser.compile_filter(bits[1])
    nodelist = parser.parse()    
    if nodelist.get_nodes_by_type(ExtendsNode):
        raise TemplateSyntaxError,"'%s' cannot appear more than once in the same template" % bits[0]
    return ThemeExtendsNode(nodelist,parent_name,parent_name_expr)
register.tag('theme_extends',do_theme_extends)

def get_theme_name():
    """
    get the theme name from settings.py
    """
    try:
        from django.conf import settings
        if settings.THEME_NAME == '':
            return 'default'
        else:
            return settings.THEME_NAME
    except:
        return 'default'   

def media_url():
    """
    Returns the common media url
    """
    try:
        from django.conf import settings
    except ImportError:
        return ''
    return settings.MEDIA_URL
media_url = register.simple_tag(media_url)


def theme_media_url():
    """
    Returns the themes media url
    """
    try:
        from django.conf import settings
    except ImportError:
        return ''
    return settings.MEDIA_URL + '/themes/'+ get_theme_name()
register.simple_tag(theme_media_url)

def theme_template_url():
    """
    Returns the themes template url
    """
    try:
        from django.conf import settings
    except ImportError:
        return ''
    return 'themes/'+ get_theme_name()
